<template>
  <div class="editAccount">
    <van-overlay :show="vLoading" style="z-index:20000">
      <van-loading style="margin-left:49%; margin-top:50%" />
    </van-overlay>
    <van-nav-bar :title="$route.query.templateName" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit" scroll-to-error label-width="9.2em" ref="form">
      <van-row type="flex" justify="space-between">
        <van-col span="12">
          <div class="title" style="margin: 12px 16px; font-size: 16px">
            投保人信息
          </div>
        </van-col>
        <van-col span="12"><van-button @click="insurerClick" native-type="button" style="float: right; margin: 4px 16px 0 0" plain hairline type="info" size="small">常用</van-button></van-col>
      </van-row>
      <van-field v-model="insureName" required label="投保人" placeholder="投保人" :rules="[{ required: true, message: '投保人' }]" />
      <van-field clickable required readonly :rules="[{ required: true, message: '请选择证件类型' }]" name="picker" :value="insureCertificateType" label="证件类型" placeholder="点击选择"
        @click="showInsurePicker = true" />
      <van-popup v-model="showInsurePicker" position="bottom">
        <van-picker show-toolbar :columns="columns.map((item) => item.label)" @confirm="onInsureConfirm" @cancel="showInsurePicker = false" />
      </van-popup>
      <van-field v-model="insureCertificateNumber" required label="证件号码" placeholder="证件号码" :rules="[
      { required: true, message: '请选择证件号码' },
      {
        validator: (value, rule) => checkDocument(value, rule),
        message: '请输入正确的证件号码',
      },
    ]" />
      <van-row type="flex" justify="space-between">
        <van-col span="12">
          <div class="title" style="margin: 12px 16px; font-size: 16px">
            被保人信息
          </div>
        </van-col>
        <van-col span="12"><van-button native-type="button" @click="insurederClick" style="float: right; margin: 4px 16px 0 0" plain hairline type="info" size="small">常用</van-button></van-col>
      </van-row>
      <van-field v-model="insuredName" required label="被保险人" placeholder="被保险人" :rules="[{ required: true, message: '被保险人' }]" />
      <van-field clickable required readonly :rules="[{ required: true, message: '请选择证件类型' }]" name="picker" :value="insuredCertificateType" label="证件类型" placeholder="点击选择"
        @click="showInsuredPicker = true" />
      <van-popup v-model="showInsuredPicker" position="bottom">
        <van-picker show-toolbar :columns="columns.map((item) => item.label)" @confirm="onInsuredConfirm" @cancel="showInsuredPicker = false" />
      </van-popup>
      <van-field v-model="insuredCertificateNumber" required label="证件号码" placeholder="请选择证件号码" :rules="[{ required: true, message: '请选择证件号码' }]" />
      <div class="title" style="margin: 12px 16px; font-size: 16px">
        联系人信息
      </div>
      <van-field v-model="contactName" required label="联系人" placeholder="请输入联系人" :rules="[{ required: true, message: '请输入联系人' }]" />
      <van-field v-model="contactPhone" required label="联系方式" placeholder="请输入联系方式" :rules="[{ required: true, message: '请输入联系方式' }]" />
      <div class="title" style="margin: 12px 16px; font-size: 16px">
        险种信息
      </div>
      <van-field readonly clickable required :rules="[{ required: true, message: '请选择险种' }]" name="picker" :value="insureKindId" label="险种选择" placeholder="点击选择险种" @click="showInsureKind = true" />
      <van-popup v-model="showInsureKind" position="bottom">
        <van-picker show-toolbar :columns="insureKindColumns" @confirm="onInsureKindConfirm" @cancel="showInsureKind = false" />
      </van-popup>
      <div class="title" style="margin: 12px 16px; font-size: 16px">
        货运信息
      </div>
      <van-field readonly clickable required :rules="[{ required: true, message: '请选择货物类型' }]" name="picker" :value="goodsType" label="货物类型" placeholder="点击选择货物类型" @click="showGoodsName = true" />
      <van-popup v-model="showGoodsName" position="bottom">
        <van-picker show-toolbar :columns="goodsNameColumns" @confirm="onGoodsNameConfirm" @cancel="showGoodsName = false" />
      </van-popup>

      <!-- <van-field v-model="tagInvoiceWaybill" :required="isHighway" rows="3" type="textarea" label="标记发票号码运单号"
        placeholder="请输入标记发票号码运单号" /> -->
      <!-- <van-field v-model="containerCount" :required="isHighway" label="包装和数量" placeholder="请输入包装和数量" :rules="[
      {
        validator: (value, rule) => checkContainerCount(value, rule),
        message: '请输入数字',
      },
    ]" /> -->

      <van-field v-model="goodsName" required rows="3" type="textarea" label="货物名称" placeholder="请输入货物名称" :rules="[{ required: true, message: '请输入货物名称' }]" />

      <van-field readonly clickable required :rules="[{ required: true, message: '请选择包装' }]" name="picker" :value="packName" label="包装" placeholder="点击选择包装" @click="showPacking = true" />
      <van-popup v-model="showPacking" position="bottom">
        <van-picker show-toolbar :columns="packingColumns" @confirm="onPackingConfirm" @cancel="showPacking = false" />
      </van-popup>

      <van-field :required="!isHighway" v-model="containerNumber" rows="3" type="textarea" @input="handleInput" label="集装箱号" placeholder="请输入集装箱号" :rules="[
      { required: !isHighway, message: '请输入集装箱号' },
      {
        validator: (value, rule) => checkContainerNumber(value, rule),
        message: '格式应为4个大写字母+7位数字',
      },
    ]" />

      <van-field readonly v-model="containerNum" label="箱量" placeholder="" />

      <!-- <van-field v-model="transportTool" :readonly="isHighway" label="运输工具" placeholder="请输入运输工具" /> -->

      <!-- <van-field v-model="shipNumber" :required="isHighway" label="车牌号" placeholder="请输入车牌号" /> -->

      <van-field readonly clickable required :rules="[{ required: true, message: '请选择运输方式' }]" name="picker" :value="transportTypeName" label="运输方式" placeholder="点击选择运输方式"
        @click="showTransMethod = true" />
      <van-popup v-model="showTransMethod" position="bottom">
        <van-picker show-toolbar :columns="transMethodColumns" @confirm="onTransMethodConfirm" @cancel="showTransMethod = false" />
      </van-popup>

      <van-field readonly clickable name="area" required :value="startPlace" label="启运地" placeholder="点击选择启运地" :rules="[{ required: true, message: '请选择启运地' }]" @click="showArea = true" />
      <van-popup v-model="showArea" position="bottom">
        <van-area columns-num="2" :area-list="areaList" @confirm="onAreaConfirm" @cancel="showArea = false" />
      </van-popup>

      <!-- <van-field readonly columns-num="2" clearable clickable name="area" :value="middlePlace" label="中转地"
        placeholder="点击选择中转地（非必填）" @click="showAfterArea = true" />
      <van-popup v-model="showAfterArea" position="bottom">
        <div style="
            position: absolute;
            top: 15px;
            font-size: 14px;
            left: 48%;
            z-index: 2000;
          " @click="() => {
        middlePlace = '';
        showAfterArea = false;
      }
      ">
          清空
        </div>
        <van-area columns-num="2" :area-list="areaList" @confirm="onAfterAreaConfirm" @cancel="showAfterArea = false" />
      </van-popup> -->

      <van-field readonly clickable name="area" required :value="endPlace" label="目的地" placeholder="点击选择目的地" :rules="[{ required: true, message: '请选择目的地' }]" @click="showEndArea = true" />
      <van-popup v-model="showEndArea" position="bottom">
        <van-area columns-num="2" :area-list="areaList" @confirm="onEndAreaConfirm" @cancel="showEndArea = false" />
      </van-popup>

      <van-field readonly required clickable name="calendar" :value="startTime" label="启运日期" placeholder="点击选择日期" @click="showCalendar = true" />
      <van-calendar v-model="showCalendar" :min-date="minDate" @confirm="onConfirm" />
      <!-- <div class="title" style="margin: 12px 16px; font-size: 16px">
        扩展保险责任
      </div>
      <van-field v-if="info.insureRateExtends && !!info.insureRateExtends.length" name="checkboxGroup" label="扩展保险">
        <template #input>
          <van-checkbox-group v-model="insureExtendIds" @change="insureExtendIdsChange">
            <van-checkbox v-for="(item, index) in info.insureRateExtends" :key="index"
              :name="String(item.insureExtendId)" style="margin-bottom: 10px" shape="square">{{ item.extendInsureName
              }}</van-checkbox>
          </van-checkbox-group>
        </template>
</van-field> -->
      <div class="title" style="margin: 12px 16px; font-size: 16px">
        费用信息
      </div>
      <van-field v-model="totalFee" @input="totalFeeChange" required label="保险金额（总货值）" placeholder="请输入保险金额（总货值）" :rules="[
      { required: true, message: '请输入保险金额（总货值）' },
      {
        validator: (value, rule) => checktotalFee(value, rule),
        message: '请输入数字',
      },
    ]" />
      <van-field required v-model="insureRate" readonly label="保险费率" />
      <van-field required v-model="insureFee" readonly label="保险费用" />
      <!-- <van-field v-model="discountRate" readonly label="已优惠费率" />
      <van-field :value="discountedFees" readonly label="已优惠费用" /> -->
      <!-- <div class="title" style="margin: 12px 16px; font-size: 16px">
        发票信息
      </div> -->
      <van-row type="flex" justify="space-between">
        <van-col span="12">
          <div class="title" style="margin: 12px 16px; font-size: 16px">
            发票信息
          </div>
        </van-col>
        <van-col v-if="invoiceStatus" span="12"><van-button native-type="button" @click="commonInvoicesClick" style="float: right; margin: 4px 16px 0 0" plain hairline type="info"
            size="small">常用</van-button></van-col>
      </van-row>
      <van-field label="是否开启发票">
        <template #input>
          <van-checkbox @change="invoiceStatusChange" v-model="invoiceStatus" name="1" shape="square">开启发票</van-checkbox>
        </template>
      </van-field>
      <van-field label="发票类型" v-if="invoiceStatus">
        <template #input>
          <van-radio-group v-model="invoiceType" direction="horizontal">
            <van-radio :name="1">普票</van-radio>
            <van-radio :name="2">专票</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <div v-if="invoiceStatus">
        <van-field v-model="invoiceHead" required label="发票抬头" :rules="[{ required: true, message: '请输入发票抬头' }]" />
        <van-field v-model="creditCode" required label="税号" :rules="[{ required: true, message: '请输入税号' }]" />
        <van-field v-model="consigneeMail" required label="收件人邮箱" :rules="[{ required: true, message: '请输入收件人邮箱' }]" />
        <van-field v-model="consigneePhone" label="收件人电话" />
        <van-field v-model="bankBranchName" label="开户银行" />
        <van-field v-model="bankAccount" label="银行账户" />
        <van-field v-model="companyPhone" label="电话号码" />
        <van-field v-model="registerAddress" label="单位地址" />
      </div>
      <div class="title" style="margin: 12px 16px; font-size: 16px">备注</div>
      <van-field v-model="remark" rows="2" autosize label="" type="textarea" maxlength="200" placeholder="备注" show-word-limit />
      <div style="padding-bottom: 10px;">
        <div style="margin: 16px" v-if="!isDetail">
          <van-button block type="info" native-type="submit">{{
      $route.query.batchOrder ? "新增批单" : "立即投保"
    }}</van-button>
        </div>
        <div style="margin: 16px" v-if="$route.query.warrantyDarftId && !$route.query.isDetail">
          <van-button block type="info" native-type="button" @click="insureAndDel">投保并删除草稿</van-button>
        </div>
        <div style="margin: 16px" v-if="!isDetail && !$route.query.batchOrder">
          <van-button native-type="button" block @click="draftClick">暂存草稿</van-button>
        </div>
      </div>
    </van-form>
    <van-popup v-model="insureShow" position="bottom" closeable :style="{ height: '60%', 'background-color': 'rgb(237 237 237)' }">
      <div style="font-size: 16px; margin: 20px 20px 14px 16px">常用投保人</div>

      <div v-if="!applicantList.length">
        <div style="font-size: 14px; padding: 20px">
          您还未添加投保人，点击可添加常用投保人
        </div>
        <van-button style="margin-left: 20px" type="primary" size="small" @click="() => {
      $router.push(
        `/addApplicant?tempInput=1&insureInfoId=${$route.query.insureInfoId}&templateName=${$route.query.templateName}`
      );
      setInsuranceDataToCache();
    }
      ">添加投保人</van-button>
      </div>
      <van-cell-group inset class="account-info" style="margin-top: 10px" v-for="(item, index) in applicantList" :key="index">
        <van-cell>
          <template #title>
            <van-checkbox @click="insureNameChange(item)" v-model="item.isTrue">{{ item.insureName }}</van-checkbox>
          </template>
        </van-cell>
        <van-cell title="证件类型" :value="item.insureCertificateType * 1 === 1 ? '身份证' : '统一社会信用代码'
      " />
        <van-cell title="证件号码" :value="item.insureCertificateNumber" />
        <van-cell title="联系人" :value="item.contactName" />
        <van-cell title="联系电话" :value="item.contactPhone" />
        <!-- <van-cell title="收货人" :value="item.consigneeName" />
        <van-cell title="收货电话" :value="item.consigneePhone" />
        <van-cell title="收货地址" :value="item.consigneeAddress" /> -->
      </van-cell-group>
      <van-row v-if="applicantList.length">
        <van-col span="24">
          <div style="float: right; margin: 16px 14px 16px 0">
            <van-button size="small" type="info" style="margin-right: 5px" @click="insureSure">确定</van-button>
            <van-button size="small" @click="() => (insureShow = false)">取消</van-button>
          </div>
        </van-col>
      </van-row>
    </van-popup>
    <van-popup v-model="insuredShow" position="bottom" closeable :style="{ height: '60%', 'background-color': 'rgb(237 237 237)' }">
      <div style="font-size: 16px; margin: 20px 20px 14px 16px">被保险人</div>
      <div v-if="!insuredList.length">
        <div style="font-size: 14px; padding: 20px">
          您还未添加被保险人，点击可添加被保险人
        </div>
        <van-button style="margin-left: 20px" type="primary" size="small" @click="() => {
      $router.push({
        path: 'applicant',
        query: {
          showInsured: true,
          insureInfoId: $route.query.insureInfoId,
          templateName: $route.query.templateName,
        },
      });
      setInsuranceDataToCache();
    }
      ">添加被保险人</van-button>
      </div>
      <van-cell-group inset class="account-info" style="margin-top: 10px" v-for="(item, index) in insuredList" :key="index">
        <van-cell>
          <template #title>
            <van-checkbox @click="insuredNameChange(item)" v-model="item.isTrue">{{ item.insuredName }}</van-checkbox>
          </template>
        </van-cell>
        <van-cell title="证件类型" :value="item.insuredCertificateType * 1 === 1
      ? '身份证'
      : '统一社会信用代码'
      " />
        <van-cell title="证件号码" :value="item.insuredCertificateNumber" />
      </van-cell-group>
      <van-row v-if="insuredList.length">
        <van-col span="24">
          <div style="float: right; margin: 16px 14px 16px 0">
            <van-button size="small" type="info" style="margin-right: 5px" @click="insuredSure">确定</van-button>
            <van-button size="small" @click="() => (insuredShow = false)">取消</van-button>
          </div>
        </van-col>
      </van-row>
    </van-popup>
    <van-popup v-model="invoicesShow" position="bottom" closeable :style="{ height: '60%', 'background-color': 'rgb(237 237 237)' }">
      <div style="font-size: 16px; margin: 20px 20px 14px 16px">发票</div>
      <div v-if="!invoicesList.length">
        <div style="font-size: 14px; padding: 20px">
          您还未添加发票，点击可添加发票
        </div>
        <van-button style="margin-left: 20px" type="primary" size="small" @click="() => {
      $router.push({
        path: 'addInvoice',
        query: {
          showInsured: true,
          insureInfoId: $route.query.insureInfoId,
          templateName: $route.query.templateName,
        },
      });
      setInsuranceDataToCache();
    }
      ">添加发票</van-button>
      </div>
      <van-cell-group inset class="account-info" style="margin-top: 10px" v-for="(item, index) in invoicesList" :key="index">
        <van-cell>
          <template #title>
            <van-checkbox @click="invoicesChange(item)" v-model="item.isTrue"></van-checkbox>
          </template>
        </van-cell>
        <van-cell title="发票抬头" :value="item.invoiceHead" />
        <van-cell title="税号" :value="item.creditCode" />
        <van-cell title="收件人邮箱" :value="item.consigneeMail" />
        <van-cell title="收件人电话" :value="item.consigneePhone" />
        <van-cell title="开户银行" :value="item.bankBranchName" />
        <van-cell title="银行账户" :value="item.bankAccount" />
        <van-cell title="电话号码" :value="item.companyPhone" />
        <van-cell title="单位地址" :value="item.registerAddress" />
      </van-cell-group>
      <van-row v-if="invoicesList.length">
        <van-col span="24">
          <div style="float: right; margin: 16px 14px 16px 0">
            <van-button size="small" type="info" style="margin-right: 5px" @click="invoicesSure">确定</van-button>
            <van-button size="small" @click="() => (invoicesShow = false)">取消</van-button>
          </div>
        </van-col>
      </van-row>
    </van-popup>
    <van-popup v-model="showPayment" position="bottom" @close="payClose" closeable :style="{ height: '70%', 'background-color': 'rgb(237 237 237)' }">
      <div style="font-size: 16px; margin: 20px 20px 14px 16px">
        订单号：{{ orderNum }}
      </div>
      <!-- 密码输入框 -->
      <div style="font-size: 16px; margin: 20px 20px 14px 16px">
        保费金额：{{ insureFee }}
      </div>
      <p v-if="!!this.$route.query.batchOrder" style="color:red;font-size: 16px; margin: 20px 20px 14px 16px ">
        批单审批通过后，原订单金额会原路退回。</p>
      <p style="color:red;font-size: 16px; margin: 20px 20px 14px 16px ">
        支付密码不是6位数字的客户，请在【管理中心】-【支付密码】中，尽快重新设置支付密码为6位数字</p>
      <van-password-input info="密码为 6 位数字" :error-info="errorInfo" :value="passwordValue" :focused="showKeyboard" />
      <!-- 数字键盘 -->
      <van-number-keyboard v-model="passwordValue" :show="showKeyboard" />
    </van-popup>

    <van-overlay :show="loading">
      <van-loading style="margin-left: 49%; margin-top: 50%" />
    </van-overlay>

    <van-popup v-model="showRecharge" position="bottom" @close="rechargeClose" closeable :style="{ height: '60%', 'background-color': 'rgb(237 237 237)' }">
      <recharge ref="recharge" @resubmit="resubmit" title="余额不足请充值"></recharge>
    </van-popup>
  </div>
</template>

<script>
import { addressObj } from "@/utils/options";
import recharge from "../../recharge.vue";
const Decimal = require("decimal.js");
const reg =
  /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;
const reg2 = /^[0-9A-Z]{18}$/;
const reg3 = /^\d+$/;
const reg4 = /^[A-Z]{4}\d{7}$/;
const reg5 = /^\d*\.?\d+$/;
import { documentType } from "@/utils/options";
import { getLabel, getValue } from "@/utils/func";
import { deepClone } from "@/utils";
import moment from "moment";
import { Dialog } from "vant";
export default {
  components: {
    recharge,
  },
  computed: {
    discountedFees() {
      const fee = ((this.discountRate * this.totalFee) / 100).toFixed(2);
      if (this.insureFee > this.minCost) {
        return fee;
      } else {
        return 0;
      }
    },
    transMethodColumns() {
      console.log("this.insureKindId", this.insureKindId);
      return this.insureKindId === "水路货运险"
        ? ["海运", "集装箱海运", "水运", "联运"]
        : ["公路"];
    },
    packingColumns() {
      const val = this.goodsType || "";
      if (val.includes("粮谷类") || val.includes("饲料类")) {
        return ["箱装", "桶装", "罐装", "散装", "袋装"];
      } else if (
        val.includes("五金类") ||
        val.includes("化工品类") ||
        val.includes("轻工品类-塑料制品") ||
        val.includes("轻工品类-轻工品类（非易碎）")
      ) {
        return ["箱装", "桶装", "罐装", "散装", "袋装", "托盘"];
      } else if (
        val.includes("机械设备类") ||
        val.includes("轻工品类-玻璃、陶瓷、搪瓷等易碎品类")
      ) {
        return ["箱装", "桶装", "盘卷包装", "散装", "袋装", "托盘"];
      } else {
        return ["箱装", "桶装", "罐装", "散装", "袋装", "托盘", "盘卷包装"];
      }
    },
    isHighway() {
      return this.$route.query.templateName.includes("公路");
    },
    containerNum: {
      get() {
        const num = this.containerNumber;
        if (!num) {
          return 0;
        }
        return num.split("\n").filter((item) => item != "").length;
      },
      set() {},
    },
    minDate() {
      const today = new Date();
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      return yesterday;
    },
  },
  watch: {
    passwordValue(value) {
      if (value.length === 6) {
        let params = {};
        let url = "";
        if (this.$route.query.batchOrder) {
          params = {
            modifyOrderNum: this.orderNum,
            walletPassword: value,
          };
          url = "/warranty/insure/modifypay";
        } else {
          params = {
            orderNum: this.orderNum,
            walletPassword: value,
          };
          url = "/warranty/insure/pay";
        }
        this.loading = true;
        this.$post(url, params)
          .then((res) => {
            if (res && res.code * 1 === 200) {
              this.$toast({
                message: "支付成功",
                duration: 800,
              });
              if (this.isInsureAndDel) {
                this.deleteDraft();
              } else {
                this.$router.push("/guaranteeSlip");
              }
            } else if (res.code * 1 === 500) {
              if (res.msg === "个人账户余额不足") {
                this.$toast({
                  message: "个人账户余额不足,请充值,充值后可在待支付里继续支付",
                  duration: 4000,
                });
                this.$router.push({
                  path: "/wallet",
                });
                // this.showRecharge = true
              } else {
                this.errorInfo = res.msg;
                this.passwordValue = "";
              }
            } else {
              this.errorInfo = res.msg;
              this.passwordValue = "";
            }
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
  },
  data() {
    return {
      vLoading: false,
      isInsureAndDel: false,
      loading: false,
      minCost: 0,

      showTransMethod: false,

      showPacking: false,
      // packingColumns: [
      // '箱装','桶装','罐装','散装','袋装','托盘','盘卷包装'
      // ],

      showRecharge: false,

      passwordValue: "",
      showKeyboard: true,
      showPayment: false,
      errorInfo: "",

      insureId: "",
      insuredId: "",
      areaList: addressObj,
      insureKindColumns: [],
      goodsNameColumns: [],
      showGoodsName: false,
      showCalendar: false,
      showArea: false,
      showAfterArea: false,
      showEndArea: false,
      columns: documentType,
      showInsurePicker: false,
      showInsuredPicker: false,
      insureName: "",
      insureCertificateType: "身份证",
      insureCertificateNumber: "",

      insuredName: "",
      insuredCertificateType: "身份证",
      insuredCertificateNumber: "",

      contactName: "", //String**联系人姓名  （必须）
      contactPhone: "", //String**联系人电话  （必须）
      insureKindId: "", //Long**险种id  （必须）
      insureGoodsId: "", //Long**货物类型id （必须）
      goodsType: "", //String**货物类型 （必须）
      containerNumber: "", //String**集装箱号 以;隔开（必须）
      // containerCount: 0, //String**包装与数量 （必须）
      // tagInvoiceWaybill: "", //String**标记发票号码运单号 （必须）
      // waybillNumber: "", //String**运单号 （必须）
      goodsName: "", //String**货物名称 （必须）
      // transportTool: "", //String**运输工具 （必须）
      // shipNumber: "", //String**车牌号 （必须）
      packName: "", //String**包装 （必须）
      transportTypeName: "", //String**运输方式 （必须）
      startPlace: "", //String**启运地 （必须）
      // middlePlace: "", //String**中转地 （必须）
      endPlace: "", //String**目的地 （必须）
      startTime: moment().format("YYYY-MM-DD"), //String**启运时间 （必须）
      insureExtendIds: [], //String**扩展保险 以;隔开（必须）
      totalFee: "", //BigDecimal**保险总金额 （必须）
      insureRate: "", //BigDecimal**保险费率 单=位%（必须）
      insureFee: "0.00", //BigDecimal**最终保费 （必须）

      invoiceStatus: false, //String**发票状态 0=不需要,1=普票,2=专票（必须）
      invoiceHead: "", // String**发票抬头
      consigneePhone: "", // String**收货人电话
      consigneeAddress: "", // String**收货人地址
      registerAddress: "", // String**注册地址
      creditCode: "", //String**统一社会信用代码
      bankAccount: "", //String**银行账号
      bankBranchName: "", //String**支行名称
      consigneeMail: "", //String**收件人邮箱
      companyPhone: "", //String**电话号码

      invoiceType: 1,

      insureShow: false,
      insuredShow: false,
      invoicesShow: false,
      showInsureKind: false,
      username: "",
      password: "",
      remark: "",
      radio: "",
      checkboxGroup: [],
      applicantList: [],
      insuredList: [],
      invoicesList: [],
      info: {},

      orderNum: "",
      oriFeeRate: "",

      isDetail: false,

      discountRate: 0,
      goStatus: 1,
    };
  },
  methods: {
    deleteDraft() {
      const url = "/warranty/darft/remove";
      const params = { warrantyDarftId: this.$route.query.warrantyDarftId };
      this.$post(url, params).then((res) => {
        if (res && res.code * 1 === 200) {
          this.$router.push("/guaranteeSlip");
        }
      });
    },
    setInsuranceDataToCache() {
      localStorage.setItem("insuranceData", JSON.stringify(this.getParams()));
    },
    onPackingConfirm(val) {
      this.packName = val;
      this.showPacking = false;
    },
    onTransMethodConfirm(val) {
      this.transportTypeName = val;
      this.showTransMethod = false;
    },
    resubmit() {
      const params = {
        orderNum: this.orderNum,
        walletPassword: this.passwordValue,
      };
      this.loading = true;
      this.$post("/warranty/insure/pay", params)
        .then((res) => {
          if (res && res.code * 1 === 200) {
            this.$toast({
              message: "支付成功",
              duration: 800,
            });
            this.$router.push("/guaranteeSlip");
          } else if (res.code * 1 === 500) {
            if (res.msg === "个人账户余额不足") {
              this.$toast({
                message: "个人账户余额不足,请充值",
                duration: 2000,
              });
              this.showRecharge = true;
            }
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    insureExtendIdsChange(names) {
      const list = this.info.insureRateExtends.filter((item) =>
        names.includes(String(item.insureExtendId))
      );
      let sum = this.oriFeeRate ? new Decimal(this.oriFeeRate) : new Decimal(0);

      list.forEach((item) => {
        sum = sum.plus(new Decimal(item.extendInsureRate)); // 使用.plus方法进行精确加法
      });
      this.insureRate = sum.toString();

      if (this.totalFee) {
        this.setInsureFee(this.totalFee);
      }
    },
    checktotalFee(val) {
      return reg5.test(val);
    },
    handleInput(value) {
      if (!value) {
        this.containerNumber = "";
        return;
      }
      if (value.replace(/\n/g, "").length % 11 === 0) {
        this.containerNumber += "\n";
      }
      this.containerNumber = this.containerNumber.replace(/(\r?\n)+/g, "\n");
    },
    checkContainerNumber(val) {
      let flag = true;
      const valArr = val.split(/\r?\n/g);
      valArr.forEach((item) => {
        if (item && !reg4.test(item)) {
          flag = false;
        }
      });
      return flag;
    },
    checkContainerCount(val) {
      return reg3.test(val);
    },
    invoiceStatusChange(val) {
      //
    },
    totalFeeChange(val) {
      if (!this.insureKindId) {
        this.$toast({
          message: "请选择险种",
          duration: 2000,
        });
        this.totalFee = "";
        return;
      }
      if (!this.goodsType) {
        this.$toast({
          message: "请选择货物类型",
          duration: 2000,
        });
        this.totalFee = "";
        return;
      }
      this.setInsureFee(val);
    },
    setInsureFee(val) {
      const num1 = new Decimal(this.insureRate);
      const num2 = val ? new Decimal(val) : Decimal(0);
      const num3 = new Decimal(100);
      const fee = num1.times(num2).dividedBy(num3).toString();
      const insureFee = Number(fee).toFixed(2);
      this.insureFee = insureFee > this.minCost ? insureFee : this.minCost;
    },
    onAfterAreaConfirm(values) {
      this.middlePlace = values
        .filter((item) => !!item)
        .map((item) => item.name)
        .join("/");
      this.showAfterArea = false;
    },
    onAreaConfirm(values) {
      console.log(values, 'values')
      this.startPlace = values
        .filter((item) => !!item)
        .map((item) => item.name)
        .join("/");
      this.showArea = false;
    },
    onEndAreaConfirm(values) {
      this.endPlace = values
        .filter((item) => !!item)
        .map((item) => item.name)
        .join("/");
      this.showEndArea = false;
    },
    onGoodsNameConfirm(val) {
      this.packName = "";
      const item = this.info.insureRateKinds.find(
        (a) => a.insureKindName === this.insureKindId
      );
      item.insureRateGoodss.forEach((e) => {
        if (e.goodsTypeName === val) {
          const num1 = new Decimal(e.goodsTypeRate);
          const num2 = new Decimal(this.discountRate);
          const num3 = num1.minus(num2).toString();
          this.insureRate = num3;
          this.oriFeeRate = deepClone(num3);
        }
      });
      this.goodsType = val;
      if (this.totalFee) {
        this.setInsureFee(this.totalFee);
      }
      this.showGoodsName = false;
    },
    onInsureKindConfirm(val) {
      this.packName = "";
      // this.transportTool = "";
      this.goodsType = "";
      this.insureRate = "";
      const item = this.info.insureRateKinds.find(
        (a) => a.insureKindName === val
      );
      if (item) {
        this.goodsNameColumns = item.insureRateGoodss.map(
          (a) => a.goodsTypeName
        );
      }
      this.insureKindId = val;
      this.showInsureKind = false;
    },
    onConfirm(date) {
      this.startTime = moment(date).format("YYYY-MM-DD");
      this.showCalendar = false;
    },
    insureSure() {
      this.applicantList.forEach((item) => {
        if (item.isTrue) {
          this.insureName = item.insureName;
          this.insureCertificateType = getLabel(
            documentType,
            item.insureCertificateType * 1
          );
          this.insureCertificateNumber = item.insureCertificateNumber;
          this.insureId = item.insureId;
          this.contactName = item.contactName;
          this.contactPhone = item.contactPhone;
          // this.getInvoiceInfo(item.insureId);
        }
      });
      this.insureShow = false;
    },
    insuredSure() {
      this.insuredList.forEach((item) => {
        if (item.isTrue) {
          this.insuredName = item.insuredName;
          this.insuredCertificateType = getLabel(
            documentType,
            item.insuredCertificateType * 1
          );
          this.insuredCertificateNumber = item.insuredCertificateNumber;
          this.insuredId = item.insuredId;
        }
      });
      this.insuredShow = false;
    },
    invoicesSure() {
      this.invoicesList.forEach((item) => {
        if (item.isTrue) {
          this.invoiceHead = item.invoiceHead;
          this.consigneePhone = item.consigneePhone;
          this.consigneeAddress = item.consigneeAddress;
          this.registerAddress = item.registerAddress;
          this.creditCode = item.creditCode;
          this.bankAccount = item.bankAccount;
          this.bankBranchName = item.bankBranchName;
          this.consigneeMail = item.consigneeMail;
          this.companyPhone = item.companyPhone;
        }
      });
      this.invoicesShow = false;
    },
    checkDocument(value, rule) {
      if (this.insureCertificateType === "身份证") {
        return reg.test(value);
      }
      return reg2.test(value);
    },
    onInsureConfirm(insureCertificateType) {
      this.insureCertificateType = insureCertificateType;
      this.showInsurePicker = false;
    },
    onInsuredConfirm(insuredCertificateType) {
      this.insuredCertificateType = insuredCertificateType;
      this.showInsuredPicker = false;
    },
    insureNameChange(item) {
      this.applicantList.forEach((a) => {
        if (a.insureId === item.insureId) {
          this.$set(item, "isTrue", !a.isTrue);
          item.isTrue = !a.isTrue;
        } else {
          this.$set(a, "isTrue", false);
          a.isTrue = false;
        }
      });
    },
    insuredNameChange(item) {
      this.insuredList.forEach((a) => {
        if (a.insureId === item.insureId) {
          this.$set(item, "isTrue", !a.isTrue);
          item.isTrue = !a.isTrue;
        } else {
          this.$set(a, "isTrue", false);
          a.isTrue = false;
        }
      });
    },
    invoicesChange(item) {
      this.invoicesList.forEach((a) => {
        if (a.invoiceId === item.invoiceId) {
          this.$set(item, "isTrue", !a.isTrue);
          item.isTrue = !a.isTrue;
        } else {
          this.$set(a, "isTrue", false);
          a.isTrue = false;
        }
      });
    },
    getApplicantList() {
      return this.$get("/config/insure/list").then((res) => {
        if (res && res.code * 1 === 200) {
          this.applicantList = res.data;
          this.applicantList.forEach((item) => {
            this.$set(item, "isTrue", false);
          });
        } else {
          this.applicantList = [];
        }
      });
    },
    getInsuredList() {
      return this.$get("/config/insured/list").then((res) => {
        if (res && res.code * 1 === 200) {
          this.insuredList = res.data;
          this.insuredList.forEach((item) => {
            this.$set(item, "isTrue", false);
          });
        } else {
          this.insuredList = [];
        }
      });
    },
    getInvoicesList() {
      return this.$get("/config/invoice/list").then((res) => {
        if (res && res.code * 1 === 200) {
          this.invoicesList = res.data;
          this.invoicesList.forEach((item) => {
            this.$set(item, "isTrue", false);
          });
        } else {
          this.invoicesList = [];
        }
      });
    },
    insurerClick() {
      this.insureShow = true;
    },
    insurederClick() {
      this.insuredShow = true;
    },
    commonInvoicesClick() {
      this.invoicesShow = true;
    },
    onClickLeft() {
      const url = window.location.hash;
      if (url.includes("orderNum") || url.includes("warrantyDarftId")) {
        this.$router.push("/guaranteeSlip");
      } else {
        this.$router.push({
          path: "temp1",
          query: {
            insureInfoId: this.$route.query.insureInfoId,
            templateName: this.$route.query.templateName,
          },
        });
      }
    },
    checkFunc() {
      // if (this.isHighway && !this.shipNumber) {
      //   this.$toast({
      //     message: "请输入车牌号",
      //     duration: 800,
      //   });
      //   return false;
      // }
      // if (this.isHighway && !this.tagInvoiceWaybill) {
      //   this.$toast({
      //     message: "请输入标记发票号码运单号",
      //     duration: 800,
      //   });
      //   return false;
      // }
      // if (this.isHighway && !this.containerCount) {
      //   this.$toast({
      //     message: "请输入包装和数量",
      //     duration: 800,
      //   });
      //   return false;
      // }
      if (!this.insureName) {
        this.$toast({
          message: "请选择投保人",
          duration: 800,
        });
        return false;
      }
      if (!this.insuredName) {
        this.$toast({
          message: "请选择被保险人",
          duration: 800,
        });
        return false;
      }

      if (!this.goodsName) {
        this.$toast({
          message: "请输入货物名称",
          duration: 800,
        });
        return false;
      }
      if (!this.goodsType) {
        this.$toast({
          message: "请选择货物类型",
          duration: 800,
        });
        return false;
      }
      // if (!this.checkContainerCount(this.containerCount)) {
      //   this.$toast({
      //     message: "箱数为数字",
      //     duration: 800,
      //   });
      //   return false;
      // }

      if (!this.isHighway && !this.containerNumber) {
        this.$toast({
          message: "请输入集装箱号",
          duration: 2000,
        });
        return false;
      }

      if (!this.checkContainerNumber(this.containerNumber)) {
        this.$toast({
          message: "格式应为4个大写字母+7位数字",
          duration: 2000,
        });
        return false;
      }
      // if (!this.waybillNumber) {
      //   this.$toast({
      //     message: "请输入运单号",
      //     duration: 800,
      //   });
      //   return false;
      // }

      if (!this.startPlace) {
        this.$toast({
          message: "请选择启运地",
          duration: 800,
        });
        return false;
      }

      if (!this.transportTypeName) {
        this.$toast({
          message: "请选择运输方式",
          duration: 800,
        });
        return false;
      }

      if (!this.endPlace) {
        this.$toast({
          message: "请选择目的地",
          duration: 800,
        });
        return false;
      }
      if (!this.startTime) {
        this.$toast({
          message: "请选择启用时间",
          duration: 800,
        });
        return false;
      }

      if (!this.totalFee) {
        this.$toast({
          message: "请输入保险总金额",
          duration: 800,
        });
        return false;
      }
      if (!this.checktotalFee(this.totalFee)) {
        this.$toast({
          message: "保险总金额为数字",
          duration: 800,
        });
        return false;
      }
      if (this.invoiceStatus && !this.invoiceHead) {
        this.$toast({
          message: "请输入发票抬头",
          duration: 800,
        });
        return false;
      }
      if (this.invoiceStatus && !this.creditCode) {
        this.$toast({
          message: "请输入税号",
          duration: 800,
        });
        return false;
      }
      if (this.invoiceStatus && !this.consigneeMail) {
        this.$toast({
          message: "请输入收件人邮箱",
          duration: 800,
        });
        return false;
      }
      return true;
    },
    draftClick() {
      if (!this.checkFunc()) {
        return;
      }
      const url = this.warrantyDarftId
        ? "/warranty/darft/update"
        : "/warranty/darft/add";
      const params = this.warrantyDarftId
        ? { ...this.getParams(), warrantyDarftId: this.warrantyDarftId }
        : this.getParams();
      if (this.vLoading) {
        return;
      }
      this.vLoading = true;
      this.$post(url, params)
        .then((res) => {
          if (res && res.code === 200) {
            this.$toast({
              message: "操作成功",
              duration: 800,
            });
            this.$router.push({
              path: "/guaranteeSlip",
              query: {
                active: 1,
              },
            });
          }
        })
        .finally(() => {
          this.vLoading = false;
        });
    },
    getParams() {
      const insureKindItem = this.info.insureRateKinds.find(
        (item) => item.insureKindName === this.insureKindId
      );
      const insureKindId = insureKindItem ? insureKindItem.insureKindId : "";
      const insureGoodsItem = insureKindItem.insureRateGoodss.find(
        (item) => item.goodsTypeName === this.goodsType
      );

      const str = this.containerNumber.replace(/(\r\n|\n|\r)/gm, ""); // 去掉换行符或回车键
      let result = "";
      for (var i = 0; i < str.length; i += 11) {
        result += str.slice(i, i + 11) + ";"; // 每11个字符用;分割
      }
      result = result.slice(0, -1); // 去掉最后一个;
      const insureGoodsId = insureGoodsItem
        ? insureGoodsItem.insureGoodsId
        : "";
      const params = {
        // tagInvoiceWaybill: this.tagInvoiceWaybill,
        goodsName: this.goodsName, //String**货物名称 （必须）
        // transportTool: this.transportTool, //String**运输工具 （必须）
        // shipNumber: this.shipNumber, //String**车牌号 （必须）
        packName: this.packName, //String**包装 （必须）
        transportTypeName: this.transportTypeName, //String**运输方式 （必须）
        // middlePlace: this.middlePlace, //String**中转地 （必须）

        insureInfoId: this.$route.query.insureInfoId,
        insureId: this.insureId,
        insuredId: this.insuredId,
        insureName: this.insureName,
        insureCertificateType: getValue(
          documentType,
          this.insureCertificateType
        ),
        insureCertificateNumber: this.insureCertificateNumber,

        insuredName: this.insuredName,
        insuredCertificateType: getValue(
          documentType,
          this.insuredCertificateType
        ),
        insuredCertificateNumber: this.insuredCertificateNumber,

        contactName: this.contactName, //String**联系人姓名  （必须）
        contactPhone: this.contactPhone, //String**联系人电话  （必须）
        insureKindId, //Long**险种id  （必须）
        insureGoodsId, //Long**货物类型id （必须）
        goodsType: this.goodsType, //String**货物类型 （必须）
        containerNumber: result, //String**集装箱号 以;隔开（必须）
        // containerCount: this.containerCount, //String**包装与数量 （必须）
        // waybillNumber: this.waybillNumber, //String**运单号 （必须）
        startPlace: this.startPlace, //String**启运地 （必须）
        endPlace: this.endPlace, //String**目的地 （必须）
        startTime: this.startTime, //String**启运时间 （必须）
        insureExtendIds: this.insureExtendIds
          ? this.insureExtendIds.join(";")
          : "", //String**扩展保险 以;隔开（必须）
        totalFee: this.totalFee, //BigDecimal**保险总金额 （必须）
        insureRate: this.insureRate, //BigDecimal**保险费率 单=位%（必须）
        insureFee: this.insureFee, //BigDecimal**余额 （必须）
        invoiceStatus: this.invoiceStatus ? this.invoiceType : 0, //String**发票状态 0=不需要,1=普票,2=专票（必须）
      };
      if (this.invoiceStatus) {
        params.consigneePhone = this.consigneePhone; // String**收货人电话
        params.consigneeAddress = this.consigneeAddress;
        params.invoiceHead = this.invoiceHead; // String**发票抬头
        params.registerAddress = this.registerAddress; // String**注册地址
        params.creditCode = this.creditCode; //String**统一社会信用代码
        params.bankAccount = this.bankAccount; //String**银行账号
        params.bankBranchName = this.bankBranchName; //String**支行名称
        params.consigneeMail = this.consigneeMail; //String**邮箱
        params.companyPhone = this.companyPhone; //String**支行名称
      }
      return params;
    },
    insureAndDel() {
      this.isInsureAndDel = true;
      this.submitFunc();
    },
    repeatConfirm() {
      this.goStatus = 0;
      this.submitFunc();
    },
    repeatcancel() {
      this.goStatus = 1;
    },
    submitFunc() {
      if (!this.checkFunc()) {
        return;
      }
      let url = "";
      let params = {};
      if (this.$route.query.batchOrder) {
        url = "/warranty/insure/modifyadd";
        params = { ...this.getParams(), orderNum: this.$route.query.orderNum };
      } else {
        url = "/warranty/insure/add";
        params = { ...this.getParams(), goStatus: this.goStatus };
      }
      if (!this.orderNum) {
        if (this.vLoading) {
          return;
        }
        this.vLoading = true;
        this.$post(url, params)
          .then((res) => {
            if (res && res.code === 200) {
              this.orderNum = res.data;
              this.showPayment = true;
              this.setOftenInsuranceData();
            } else {
              if (res && res.code === 9000) {
                Dialog.confirm({
                  title: "提示",
                  message: res.msg,
                })
                  .then(() => {
                    this.goStatus = 0;
                    this.submitFunc();
                  })
                  .catch(() => {
                    this.goStatus = 1;
                  });
              }
            }
          })
          .finally(() => {
            this.vLoading = false;
          });
      } else {
        this.showPayment = true;
      }
    },
    getWallerData() {
      return this.$post("/customer/wallet/info").then((res) => {
        if (res && res.code * 1 === 200) {
          return res.data.walletPassSatus;
        }
      });
    },
    onSubmit() {
      this.getWallerData().then((res) => {
        if (res) {
          this.isInsureAndDel = false;
          this.submitFunc();
        } else {
          this.$toast({
            message:
              "系统监测您还未设置支付密码，请先设置支付密码,可在待支付中继续支付",
            duration: 4000,
          });
          this.$router.push({
            path: "/retrievePassword",
          });
        }
      });
    },

    payClose() {
      this.showPayment = false;
      this.passwordValue = "";
    },

    rechargeClose() {
      this.$refs.recharge.initAmount();
      this.passwordValue = "";
    },

    getInfo() {
      const insureInfoId = this.$route.query.insureInfoId;
      return this.$get("/index/info", { insureInfoId }).then((res) => {
        if (res && res.code * 1 === 200) {
          this.info = res.data.data;

          this.minCost = res.data.data.minInsureFee;

          this.insureKindColumns = this.info.insureRateKinds.map(
            (item) => item.insureKindName
          );
          this.insureKindId =
            this.insureKindColumns &&
            this.insureKindColumns.length &&
            this.insureKindColumns[0];

          this.goodsNameColumns =
            this.info.insureRateKinds && this.info.insureRateKinds.length
              ? this.info.insureRateKinds[0].insureRateGoodss.map(
                  (item) => item.goodsTypeName
                )
              : [];
        } else {
          this.info = {};
        }
        return this.info;
      });
    },
    getInvoiceInfo(insureId) {
      this.$get("/config/invoice/getInfo", { insureId }).then((res) => {
        if (res && res.code * 1 === 200) {
          this.invoiceHead = res.data.invoiceHead;
          this.consigneePhone = res.data.consigneePhone;
          this.consigneeAddress = res.data.consigneeAddress;
          this.registerAddress = res.data.registerAddress;
          this.creditCode = res.data.creditCode;
          this.bankAccount = res.data.bankAccount;
          this.bankBranchName = res.data.bankBranchName;
        }
      });
    },
    getDetail() {
      this.$post("/warranty/insure/info", {
        orderNum: this.$route.query.orderNum,
      }).then((res) => {
        if (res && res.code * 1 === 200) {
          this.setDetail(res);
        }
      });
    },
    getDraftDetail() {
      this.$get("/warranty/darft/info", {
        warrantyDarftId: this.$route.query.warrantyDarftId,
      }).then((res) => {
        if (res && res.code * 1 === 200) {
          this.setDetail(res);
        }
      });
    },
    getModifyOrderDetail() {
      this.$get("/warranty/insure/modifyinfo", {
        modifyOrderNum: this.$route.query.modifyOrderNum,
      }).then((res) => {
        if (res && res.code * 1 === 200) {
          this.setDetail(res);
        }
      });
    },
    setDetail(res) {
      let startTime = "";
      const time = res.data.startTime;
      const today = moment().format("YYYY-MM-DD");
      const yesterday = moment().subtract(1, "days").format("YYYY-MM-DD");

      if (time) {
        if (moment(yesterday).isBefore(time)) {
          startTime = time;
        } else if (moment(yesterday).isAfter(time)) {
          startTime = today;
        } else {
          startTime = yesterday;
        }
      }
      const item = this.info.insureRateKinds.find(
        (a) => a.insureKindId === res.data.insureKindId
      );

      const insureGoodsItem = item.insureRateGoodss.find(
        (a) => a.insureGoodsId === res.data.insureGoodsId
      );

      const insureExtendIds = res.data.insureExtendIds
        ? res.data.insureExtendIds.split(";").map((item) => Number(item))
        : [];

      this.insureInfoId = res.data.insureInfoId;
      this.insureId = res.data.insureId;
      this.insuredId = res.data.insuredId;
      this.insureName = res.data.insureName;
      this.insureCertificateType = getLabel(
        documentType,
        res.data.insureCertificateType * 1
      );
      this.insureCertificateNumber = res.data.insureCertificateNumber;
      this.insuredName = res.data.insuredName;
      this.insuredCertificateType = getLabel(
        documentType,
        res.data.insuredCertificateType * 1
      );
      this.insuredCertificateNumber = res.data.insuredCertificateNumber;
      this.contactName = res.data.contactName;
      this.contactPhone = res.data.contactPhone;

      // this.tagInvoiceWaybill = res.data.tagInvoiceWaybill;
      this.goodsName = res.data.goodsName; //String**货物名称 （必须）
      // this.transportTool = res.data.transportTool; //String**运输工具 （必须）
      // this.shipNumber = res.data.shipNumber; //String**车牌号 （必须）
      this.packName = res.data.packName; //String**包装 （必须）
      this.transportTypeName = res.data.transportTypeName; //String**运输方式 （必须）
      // this.middlePlace = res.data.middlePlace; //String**中转地 （必须）

      this.insureKindId = item.insureKindName || "";
      this.insureGoodsId = res.data.insureGoodsId;
      this.goodsType = insureGoodsItem ? insureGoodsItem.goodsTypeName : "";
      this.containerNumber = res.data.containerNumber.replace(/;/g, "\n");
      // this.containerCount = res.data.containerCount;
      // this.waybillNumber = res.data.waybillNumber;
      // this.shipNumber = res.data.shipNumber;
      this.startPlace = res.data.startPlace;
      this.endPlace = res.data.endPlace;
      this.startTime = startTime;
      this.insureExtendIds = insureExtendIds;
      this.totalFee = res.data.totalFee;
      this.oriFeeRate = deepClone(res.data.insureRate);
      this.insureRate = res.data.insureRate;
      this.insureFee = res.data.insureFee;
      this.invoiceStatus = !!(res.data.invoiceStatus * 1);
      this.invoiceType = res.data.invoiceStatus * 1

      if (this.invoiceStatus) {
        this.invoiceHead = res.data.invoiceHead;
        this.consigneePhone = res.data.consigneePhone;
        this.consigneeMail = res.data.consigneeMail;
        this.consigneeAddress = res.data.consigneeAddress;
        this.registerAddress = res.data.registerAddress;
        this.creditCode = res.data.creditCode;
        this.bankAccount = res.data.bankAccount;
        this.bankBranchName = res.data.bankBranchName;
      }
    },
    getVipInfo() {
      this.$get("/customer/getVipInfo").then((res) => {
        if (res && res.code * 1 === 200) {
          this.discountRate = res.data.discountRate;
        }
      });
    },
    getAccountInfo() {
      const params = {
        insureName: this.insureName,
        insureCertificateType: getValue(
          documentType,
          this.insureCertificateType
        ),
        insureCertificateNumber: this.insureCertificateNumber,

        insuredName: this.insuredName,
        insuredCertificateType: getValue(
          documentType,
          this.insuredCertificateType
        ),
        insuredCertificateNumber: this.insuredCertificateNumber,

        contactName: this.contactName, //String**联系人姓名  （必须）
        contactPhone: this.contactPhone, //String**联系人电话  （必须）
      };
      return params;
    },
    setAccountInfo(data) {
      this.insureName = data.insureName;
      this.insureCertificateType = getLabel(
        documentType,
        data.insureCertificateType * 1
      );
      this.insureCertificateNumber = data.insureCertificateNumber;
      this.insuredName = data.insuredName;
      this.insuredCertificateType = getLabel(
        documentType,
        data.insuredCertificateType * 1
      );
      this.insuredCertificateNumber = data.insuredCertificateNumber;
      this.contactName = data.contactName;
      this.contactPhone = data.contactPhone;
    },
    setOftenInsuranceData() {
      localStorage.setItem(
        "oftenInsuranceData",
        JSON.stringify(this.getAccountInfo())
      );
    },
    setOftenInvoiceData() {
      localStorage.setItem(
        "oftenInvoiceData",
        JSON.stringify(this.getInvoiceData())
      );
    },
    getInvoiceData() {
      return {
        invoiceStatus: this.invoiceStatus, //String**发票状态 0=不需要,1=普票,2=专票（必须）
        invoiceHead: this.invoiceHead, // String**发票抬头
        consigneePhone: this.consigneePhone, // String**收货人电话
        consigneeAddress: this.consigneeAddress, // String**收货人地址
        registerAddress: this.registerAddress, // String**注册地址
        creditCode: this.creditCode, //String**统一社会信用代码
        consigneeMail: this.consigneeMail, //String**收件人邮箱
        companyPhone: this.companyPhone, //String**电话号码
        bankAccount: this.bankAccount, //String**银行账号
        bankBranchName: this.bankBranchName, //String**支行名称
      };
    },
    setInvoiceData(data) {
      this.invoiceStatus = data.invoiceStatus || false; //String**发票状态 0=不需要,1=普票,2=专票（必须）
      this.invoiceHead = data.invoiceHead; // String**发票抬头
      this.consigneePhone = data.consigneePhone; // String**收货人电话
      this.consigneeAddress = data.consigneeAddress; // String**收货人地址
      this.registerAddress = data.registerAddress; // String**注册地址
      this.creditCode = data.creditCode; //String**统一社会信用代码
      this.consigneeMail = data.consigneeMail; //String**收件人邮箱
      this.companyPhone = data.companyPhone; //String**电话号码
      this.bankAccount = data.bankAccount; //String**银行账号
      this.bankBranchName = data.bankBranchName; //String**支行名称
    },
    getInsureId() {
      this.applicantList.forEach(item => {
        if (item.insureName === this.insureName && item.insureCertificateNumber === this.insureCertificateNumber && item.contactName === this.contactName && item.contactPhone === this.contactPhone) {
          this.insureId = item.insureId
        }
      })
    },
    getInsuredId() {
      this.insuredList.forEach(item => {
        if (item.insuredName === this.insuredName && item.insuredCertificateNumber === this.insuredCertificateNumber) {
          this.insuredId = item.insuredId
        }
      })
    }
  },
  mounted() {
    if (this.isHighway) {
      // this.transportTool = "汽车";
    }

    const oftenInsuranceData = localStorage.getItem("oftenInsuranceData");
    if (oftenInsuranceData) {
      this.setAccountInfo(JSON.parse(oftenInsuranceData));
    }

    if (this.$route.query.templateName === "集装箱货运险") {
      this.transportTypeName = "集装箱海运";
    } else {
      this.transportTypeName = "公路";
    }

    window.scrollTo(0, 0);
    this.getInvoicesList().then(() => {
      const oftenInvoiceData = localStorage.getItem("oftenInvoiceData");

      if (oftenInvoiceData) {
        this.setInvoiceData(JSON.parse(oftenInvoiceData));
      } else {
        if (this.invoicesList.length) {
          this.setInvoiceData(this.invoicesList[0]);
        }
      }
    });
    Promise.all([this.getApplicantList(), this.getInsuredList()]).then(() => {
      const oftenInsuranceData = localStorage.getItem("oftenInsuranceData");
      if (oftenInsuranceData) {
        this.setAccountInfo(JSON.parse(oftenInsuranceData));
      } else {
        if (this.applicantList.length) {
          this.insureName = this.applicantList[0].insureName;
          this.insureCertificateType =
            this.applicantList[0].insureCertificateType;
          this.insureCertificateNumber =
            this.applicantList[0].insureCertificateNumber;

          this.contactName = this.applicantList[0].contactName;
          this.contactPhone = this.applicantList[0].contactPhone;
        }

        if (this.insuredList.length) {
          this.insuredName = this.insuredList[0].insuredName;
          this.insuredCertificateType =
            this.insuredList[0].insuredCertificateType;
          this.insuredCertificateNumber =
            this.insuredList[0].insuredCertificateNumber;
        }
      }
      this.getInsureId()
      this.getInsuredId()
    });
    this.getInfo().then((res) => {
      if (this.$route.query.orderNum) {
        this.getDetail();
      }
      if (this.$route.query.warrantyDarftId) {
        if (!this.$route.query.copy) {
          this.warrantyDarftId = this.$route.query.warrantyDarftId;
        }
        if (this.$route.query.isDetail) {
          this.isDetail = true;
        } else {
          this.isDetail = false;
        }
        this.getDraftDetail();
      }
      if (this.$route.query.getInsuredDataFromCache) {
        const insuredData = localStorage.getItem("insuranceData");
        this.setDetail({ data: JSON.parse(insuredData) });

        if (
          JSON.parse(insuredData) &&
          !JSON.parse(insuredData).insureName &&
          this.applicantList.length
        ) {
          this.insureName = this.applicantList[0].insureName;
          this.insureCertificateType =
            this.applicantList[0].insureCertificateType;
          this.insureCertificateNumber =
            this.applicantList[0].insureCertificateNumber;

          this.contactName = this.applicantList[0].contactName;
          this.contactPhone = this.applicantList[0].contactPhone;
        }

        if (
          JSON.parse(insuredData) &&
          !JSON.parse(insuredData).insuredName &&
          this.insuredList.length
        ) {
          this.insuredName = this.insuredList[0].insuredName;
          this.insuredCertificateType =
            this.insuredList[0].insuredCertificateType;
          this.insuredCertificateNumber =
            this.insuredList[0].insuredCertificateNumber;
        }

        if (
          JSON.parse(insuredData) &&
          !JSON.parse(insuredData).invoiceHead &&
          this.invoicesList.length
        ) {
          this.setInvoiceData(this.invoicesList[0]);
        }
      }
      this.getVipInfo();
    });
  },
};
</script>
<style scoped>
.editAccount {
  background-color: #f5f5f5;
  /* height: 100%; */
  width: 100%;
}
</style>

<style>
.van-key__wrapper {
  text-align: center !important;
}

.van-password-input__item i {
  margin-top: 0;
}

.van-overlay {
  z-index: 3000;
}
</style>
